package com.qlslylq.ad.sdk.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Google Gson转换工具类<br/>
 */
public class GsonUtils {

    private static Gson gson = null;

    static {
        if (gson == null) {
            //            gson = new GsonBuilder().disableHtmlEscaping().create();
            gson = new Gson();
        }
    }

    private GsonUtils() {

    }

    public static Gson getGson() {
        if (gson == null) {
//            gson = new GsonBuilder().disableHtmlEscaping().create();
            gson = new Gson();
        }
        return gson;
    }

    /**
     * 对象转成json
     */
    public static String gsonString(Object object) {
        String gsonString = null;
        if (gson != null) {
            gsonString = gson.toJson(object);
        }
        return gsonString;
    }

    /**
     * Json转成对象
     */
    public static <T> T gsonToBean(String gsonString, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * json转成list<T>
     */
    public static <T> List<T> gsonToList(String gsonString, Class<T> cls) {
        List<T> list = new ArrayList<>();
        if (gson != null) {
            list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
            }.getType());
        }
        return list;
    }

    /**
     * json转成list<T>
     */
    public static <T> List<T> gsonToListByArrays(String gsonString, Class<T[]> cls) {
        T[] arr = new Gson().fromJson(gsonString, cls);
        return Arrays.asList(arr);
    }

    /**
     * json转成list<T>
     */
    public static <T> List<List<?>> gsonToListGroup(String json, Class<T> cls) {
        List<List<?>> list = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, new TypeToken<List<T>>() {
            }.getType()));
        }
        return list;
    }

    /**
     * json转成list中有map的
     */
    public static <T> List<Map<String, T>> gsonToListMaps(String gsonString) {
        List<Map<String, T>> list = new ArrayList<>();
        if (gson != null) {
            list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
            }.getType());
        }
        return list;
    }

    /**
     * json转成map的
     */
    public static <T> Map<String, T> gsonToMaps(String gsonString) {
        Map<String, T> map = new HashMap<>();
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }
}